import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

import org.bson.*;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;

import java.util.ArrayList;
import java.util.List;


public class MyDbtest {

    /**
     * 获取远程数据库的文档信息和内容
     */
    public static void mytest() {
        ServerAddress serverAddress = new ServerAddress("100.0.0.89", 27017);
        List<ServerAddress> addrs = new ArrayList<ServerAddress>();
        addrs.add(serverAddress);
        //下面这句，是哪个库的用户，必须在其下面认证才行，我这个用户是dbowner最高权限，所以在要mydbtest下认证，这个地方折腾了好久：（
        MongoCredential credential = MongoCredential.createScramSha1Credential("sa", "mydbtest", "aaaa".toCharArray());
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        credentials.add(credential);

        MongoClient mongoClient = new MongoClient(addrs, credentials);
        MongoDatabase db = mongoClient.getDatabase("mydbtest");
//         MongoCollection coll = db.getCollection("person");
//         List<Document> list = new ArrayList<Document>();
//
//
//         Document document = new Document();
//         document.append("username","李四").append("age",25).append("adress","昌盛路三十二号");
//        Document document1 = new Document();
//        document1.append("username","黎明").append("age",20).append("adress","长江路三十八号");
//        Document document2 = new Document();
//        document2.append("username","王丽").append("age",21).append("adress","滨河路十九号");
//        list.add(document);
//        list.add(document1);
//        list.add(document2);
////         coll.insertOne(document);
//        coll.insertMany(list);


        //db.createCollection("person");
        MongoCollection<Document> collection = db.getCollection("person");
        Document documentSort = new Document();
        documentSort.append("age",1);
        FindIterable<Document> findIterable = collection.find().sort(documentSort);
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println("文档信息：" + mongoCursor.next());
        }
    }

    public static void main(String[] args) {
        mytest();
        //  System.out.println("23432");


    }


}
